package com.hmall.search.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmall.common.PageDTO;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Saint.Martine
 * @since 2022/12/10 16:21
 */
@Slf4j
@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    //自动补全
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestion1",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestion1");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //聚合
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            //创建请求
            SearchRequest request = new SearchRequest("item");
            //设置参数
            bulidBaseRequest(requestParams, request);
            request.source().size(0);//不在结果中显示文档具体内容
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(50)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("priceAgg").field("priceName").size(50)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(50)
            );
            //执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //处理结果
            List<String> categoryList = fetchAggs(response, "categoryAgg");
            List<String> priceAgglist = fetchAggs(response, "priceAgg");
            List<String> brandAggList = fetchAggs(response, "brandAgg");
            Map<String, List<String>> map = new HashMap<>();
            map.put("category", categoryList);
            map.put("price", priceAgglist);
            map.put("brand", brandAggList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //搜索
    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            //设置请求参数
            bulidBaseRequest(params, request);
            log.info("设置请求参数成功");

            //排序
            if (!StringUtils.isBlank(params.getSortBy())) {
                if ("sold".equals(params.getSortBy())) {
                    request.source().sort(params.getSortBy(), SortOrder.DESC);//评价排序
                }
                if ("price".equals(params.getSortBy())) {//价格排序
                    request.source().sort(params.getSortBy(), SortOrder.ASC);
                }
            }
            // 2.2.分页
//            int page = params.getPage();
//            int size = params.getSize();
//            request.source().from((page - 1) * size).size(size);
            request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());
            //高亮显示
            request.source().highlighter(
                    new HighlightBuilder().field("name").requireFieldMatch(false)
            );
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            log.info("发送请求成功");
            // 4.解析响应
            PageDTO<ItemDoc> pageDTO = processResponse(response);
            log.info("解析响应完成");
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //上架 数据同步
    @Override
    public void saveItemById(Long id) {
        try {
            Item item = itemClient.getById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String json = JSON.toJSONString(itemDoc);
            //创建请求
            IndexRequest request = new IndexRequest("item").id(id.toString());
            //设置参数
            request.source(json, XContentType.JSON);
            //执行请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //下架 数据同步
    @Override
    public void deleteItemById(Long id) {
        try {
            //创建请求
            DeleteRequest request = new DeleteRequest("item", id.toString());
            //执行请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    //获取聚合结果
    private List<String> fetchAggs(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    // 结果解析
    private PageDTO<ItemDoc> processResponse(SearchResponse response) {
        PageDTO<ItemDoc> pageDTO = new PageDTO<ItemDoc>();
        //数据集合
        List<ItemDoc> list = new ArrayList<>();
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        TotalHits total = searchHits.getTotalHits();
        pageDTO.setTotal(total.value);
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSONObject.parseObject(json, ItemDoc.class);

            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField nameField = highlightFields.get("name");
                String highLightName = nameField.getFragments()[0].string();
                System.out.println("高亮后的商品名称：" + highLightName);
                itemDoc.setName(highLightName);
            }
            // 放入集合
            list.add(itemDoc);
        }
        pageDTO.setList(list);
        log.info("添加到返回结果成功");
        // 4.4.封装返回
        return pageDTO;
    }

    private void bulidBaseRequest(RequestParams params, SearchRequest request) {
        //关键字查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(params.getKey())) {
            //如果key空 无条件查询
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            //key 不为空 在all 搜条件
            boolQuery.must(QueryBuilders.matchQuery("name", params.getKey()));
        }
        //多条件查询 分类 品牌 价格
        if (StringUtils.isNotBlank(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        //设置整体查询
        request.source().query(boolQuery);
    }
}
